import { useLocation } from "react-router-dom";
import styles from "../css/SearchPage.module.scss"
import HeaderList from "../components/HeaderList";
import AddIssueBtn from "../components/AddIssueBtn";
import Recommend from "../components/Recommend";
import ScoreRank from "../components/ScoreRank";
import { useEffect, useState } from "react";
import { getIssue } from "../api/issue";
import SearchResultItem from "../components/SearchResultItem";
import { ISearchResult } from "../typings"

interface IParams {
    value: string,
    searchOption: string
}
const Search = () => {
    const location = useLocation();
    // 存储搜索结果
    const [searchResult, setSearchResult] = useState<ISearchResult[]>([])
    const [pageInfo, setPageInfo] = useState({
        current: 1,
        pageSize: 5, //每页显示15条数据
        total: 0
    })

    useEffect(() => {
        const fetchData = async (params: IParams) => {
            const { value, searchOption } = params;
            let searchParams = {
                current: pageInfo.current,
                pageSize: pageInfo.pageSize,
                issueStatus: true,
                issueTitle: ""
            }
            switch (searchOption) {
                case "issue": {
                    searchParams.issueTitle = value;
                    const { data } = await getIssue(searchParams)
                    // 更新搜索结果
                    setSearchResult(data.data.data)
                    // 更新分页信息
                    setPageInfo({
                        current: data.data.currentPage,
                        pageSize: data.data.eachPage,
                        total: data.data.count
                    })
                    break;
                }
                case "book": {

                    break;
                }
            }
        }
        if (location.state) {
            fetchData(location.state);
        }
    }, [location.state])

    return (
        <div className="container">
            <HeaderList title="搜索结果" />
            <div className={styles.searchPageContainer}>
                {/* 左边部分 */}
                <div className={styles.leftSide}>
                    {searchResult.map((item) => {
                        return <SearchResultItem key={item._id} info={item} />
                    })}
                </div>
                {/* 右边部分 */}
                <div className={styles.rightSide}>
                    <AddIssueBtn />
                    <div style={{ marginBottom: "20px" }}>
                        <Recommend />
                    </div>
                    <ScoreRank />
                </div>
            </div>
        </div>
    );
}

export default Search;